# coding=utf-8
import sys
from function_utils import Global, Common, Human

store_file = 'system_info.log'
tar_file = 'oam_collect_sys_info.tar.gz'
commands = [
    ("[Linux Info]", "uname -a"),
    ("[CPU Info]", "lscpu"),
    ("[Memory Info]", "cat /proc/meminfo && free -m"),
    ("[Disk Info]", "df -h"),
    ("[IP/Route Info]", "ip a && ip r"),
    ("[Process Info]", "ps aux"),
    ("[IO Info]", '''for dev in $(ls /sys/block/); do echo "/sys/block/$dev/queue/scheduler=\
    $(cat /sys/block/$dev/queue/scheduler)"; done '''),
    ("[Ports Info]", "netstat -atnp; netstat -aunp")
]


def collect_info():
    Common.execute_cmd("date +'%F %T' >{0}".format(store_file))
    opts = Global.values_parse(sys.argv[2])[1]['Checkbox']
    for i, var in enumerate(opts):
        if not var:
            continue
        print('%s Collecting %s' % (Human.time(), commands[i][0]))
        cmd = '{ echo %s ----------------; %s; } >>%s' % (commands[i][0], commands[i][1], store_file)
        ret, out, err = Common.execute_cmd(cmd)
        if not ret:
            print(err)

    cmd = 'cd {1} && tar zcvf {0} * && chmod 777 {0}'.format(tar_file, Global.task_path)
    ret, out, err = Common.execute_cmd(cmd)
    if not ret:
        print(err)
    return ret


def write_widgets_value(ret, file):
    Global.values_write([
        {},
        {}
    ])
    if ret:
        Global.report_info(100, download=file)
    else:
        Global.report_err(100)


def main():
    if sys.argv[1] == 'start':
        write_widgets_value(collect_info(), '{0}/{1}'.format(Global.task_path, tar_file))


if __name__ == '__main__':
    main()
